Skip to content

Client: run response continuations on the receive loop thread once it waits (.NET 11 spurious wake-ups) - #5084

Merged
romanett merged 5 commits into
masterfrom
romanett/net11-response-continuations
Nov 14, 2026
Merged

romanett merged 5 commits into
masterfrom
romanett/net11-response-continuations

Conversation

@romanett

@romanett romanett commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #5078 (.NET 11 thread-pool spinning after spurious wake-ups, dotnet/runtime#137494).

Change

A request waits for its response on a ManualResetValueTaskSourceCore with RunContinuationsAsynchronously (the receive loop completes it under the channel gate). The BCL queues that continuation with preferLocal: true, so either the receive loop's thread runs it once its next receive goes pending, or a worker that the enqueue woke takes it. When the loop's thread runs it, the woken worker found no work, and on .NET 11 it spins up to 1024 backoff units before it blocks.

The receive loop now defers the completion of a response (ResponseContinuationDeferral, a thread-static slot filled in a scope around the synchronous part of OnChunkReceivedAsync) and completes it on its own thread when one of its waits (write capacity, next receive, chunk dispatch) goes pending:

  • The loop's awaits use an awaiter that first registers the loop's continuation on the pending wait and then runs the deferred continuation inline. The loop no longer depends on the thread at that point, so a continuation that blocks (for example a synchronous call on the same channel) cannot stall the receive loop; this is the same exposure as a pool thread today. BlockingContinuationDoesNotStallTheLoopAsync covers it (it fails when the two steps are swapped).
  • Never under the gate or a lock: completions run after OnChunkReceivedAsync returned.
  • A thread holds at most one deferred completion. A later response completes the held one on the pool, as before this change: a continuation run inline may block until another of its requests completes, and that one must not wait behind the blocked thread (ContinuationBlockingOnTheNextResponseDoesNotDeadlockAsync).
  • A held completion also goes to the pool once the loop dispatched 4 more chunks without its receive going pending, so a channel whose receives keep completing synchronously does not hold a response back.
  • A loop that ends completes the held one on the pool, in a finally of the loop method itself (it runs on the thread that dispatched the last chunk).
  • A loop that resumed inside another loop's dispatch on the same thread leaves the inline completion to the outer loop, which may hold locks.
  • Timeouts, cancellation and Dispose still complete the wait directly.

Client thread-pool work items per request: 2 → 1.

Measurements

After the review fixes (one held completion; run 4, medians of 4 rotated rounds, vs #5078 tip):

Scenario net11 client CPU/op net11 throughput net10 client CPU/op net10 throughput
Read 1 value 43.6 → 40.5 (−7 %) +2 % 38.7 → 35.7 (−8 %) +3 %
Write 100 175.1 → 140.4 (−20 %) +1 % 114.9 → 99.4 (−13 %) +2 %
Browse 133.1 → 95.2 (−28 %) +2 % 79.2 → 70.7 (−11 %) −2 %
Read 100, encrypt 113.8 → 109.5 (−4 %) +1 % 97.3 → 92.0 (−5 %) +2 %
Read 100, encrypt, 4 cores 140.2 → 139.4 (−1 %) 0 % 113.6 → 105.1 (−7 %) +1 %

Client work items per request 2.0 → 1.0 in every case. Earlier runs of the first version (up to 16 held completions) follow.

Load harness, 24 logical processors, 20 sessions, 12 s + 6 s warm-up, medians of 4 rotated rounds per side, runs with more than 3 cores of foreign CPU discarded. Baseline = #5078 branch tip (c1d9d6b). Client CPU in µs per operation, usr = user-mode µs/op, wi = thread-pool work items/op. "4 cores" = --client-cores 20 (server on the remaining 4 processors, encrypted).

.NET 11 (run 2 / confirming run 3):

Scenario Client CPU/op Client usr/op Client wi/op Throughput Server CPU/op
Read 1 value 42.4 → 40.3 (−5 %) / 44.2 → 40.8 (−8 %) −7 % / −10 % 2.0 → 1.0 +1 % / +2 % +1 % / +3 %
Write 100 159.8 → 130.9 (−18 %) −20 % 2.0 → 1.0 0 % 0 %
Browse 131.3 → 99.8 (−24 %) / 129.6 → 99.3 (−23 %) −26 % / −27 % 2.0 → 1.0 +8 % / +2 % +1 % / −3 %
Read 100, encrypt 115.2 → 108.2 (−6 %) / 123.6 → 111.6 (−10 %) −10 % / −6 % 2.0 → 1.0 −2 % / +1 % +4 % / −4 %
Read 100, encrypt, 4 cores 141.5 → 139.3 (−2 %) / 148.2 → 136.4 (−8 %) +18 % / −7 % 2.0 → 1.0 +1 % / +2 % −2 % / −2 %

.NET 10 (run 2):

Scenario Client CPU/op Client wi/op Throughput
Read 1 value 37.6 → 34.9 (−7 %) 2.0 → 1.0 +1 %
Write 100 95.3 → 91.4 (−4 %) 2.0 → 1.0 +2 %
Browse 76.9 → 68.1 (−11 %) 2.0 → 1.0 +1 %
Read 100, encrypt 101.7 → 98.9 (−3 %) 2.0 → 1.0 −1 %
Read 100, encrypt, 4 cores 103.2 → 99.2 (−4 %) 2.0 → 1.0 −1 %

The encrypted scenario moves ±5 % between identical builds (A/A spread in these runs), so −2 %/−1 % there is noise; the confirming .NET 11 run was +1 %.

Dropped: server writer started at the worker's park point

The second follow-up of #5078 was implemented and measured, and is not included. BeginWriteSymmetricMessage deferred ScheduleWriter() while a request worker ran a request synchronously; the worker started the deferred writers inline when it found no request (before the fair queue spins), when a request went asynchronous, when it handed back its permit (per-request dispatch), or after 1–2 more requests, and only on threads the pool dispatched it on.

Server work items per request fell by 32–53 %, but .NET 11 server CPU per request did not follow:

.NET 11, vs #5078 Read 1 Browse Read 100 encrypt Read 100 encrypt, 4 cores Write 100
Server CPU/op, bound 2 (run 1 / run 2) −8 % / −8 % +11 % / +7 % −2 % / −3 % 0 % 0 % / +3 %
Throughput, bound 2 −5 % / −5 % +7 % / +4 % −2 % / −5 % +1 % / +3 % 0 % / −2 %
Server CPU/op / throughput, bound 1 −7 % / −2 % 0 % / +1 % −1 % / −1 % +1 % / +1 % (p99 +73 %) –
Server CPU/op / throughput, park only −3 % / −5 % +3 % / −2 % 0 % / −1 % 0 % / +1 % –

It also raised client CPU per Read by 11–30 % (responses leave later and in bursts). Write kept 4 work items per request: its responses are sent after the handler went asynchronous. So the queued writer is not where the server's .NET 11 spin cost is, and deferring it costs latency and closed-loop throughput.

Tests

  • New ResponseContinuationDeferralTests (deferral in and out of scope, inline completion, completion on loop exit, one held completion, the 4-chunk bound, blocking continuation vs. loop, continuation blocking on the next response).
  • After the review fixes: Opc.Ua.Core.Tests (Stack.*) 3411 and Opc.Ua.Client.Tests 3842 passed on net10.0 and net11.0.
  • Opc.Ua.Core.Tests (Stack.Transport/Server/Client/Tcp/Bindings): 3409 passed on net10.0 and net11.0.
  • Opc.Ua.Client.Tests: 3839 passed on net10.0 and net11.0.
  • Opc.Ua.Server.Tests: 11034 passed; 8 failures in PhysicalFileSystemProviderConfinementTests on both runtimes, all "insufficient privileges" creating symbolic links on the local machine, unrelated to this change.
  • net48 build of Opc.Ua.Core.Tests.

🤖 Generated with Claude Code

…waits

A request waits for its response on a value task source that runs its
continuation asynchronously: the receive loop completes it under the channel
gate. The source queues the continuation with preferLocal, so the loop's
thread runs it once the next receive goes pending, or a worker that the
enqueue woke takes it. When the loop's thread runs it, the woken worker found
no work, and on .NET 11 such a worker spins up to 1024 backoff units.

The receive loop now defers the completions of the responses in a chunk and
completes them on its thread when one of its waits goes pending, after it
registered its continuation on that wait. The loop then no longer depends on
the thread, so a continuation that blocks, for example a synchronous call on
the same channel, cannot stall it. At most 16 completions are deferred; a
loop that ends completes them on the pool.

Client work items per request drop from 2 to 1. Client CPU per request on
.NET 11 -5 to -24 %, on .NET 10 -3 to -11 %; throughput -2 to +8 % (within
the noise of the encrypted scenario, +1 to +2 % in the confirming run).

Starting the server writer at the request worker's park point instead of
queueing it was measured as well and dropped: server work items per request
fell by a third to a half, but CPU per request did not fall consistently and
single-value Read lost 2-5 % throughput.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings November 13, 2026 17:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

…d response

ResponseAfterChannelClosedIsDroppedQuietlyAsync completed the pending
response as soon as the client's CloseAsync returned. The client does not
wait for the server to process the close, so on a slow runner the server
channel was still open, the response was queued normally and the expected
"channel closed by the client" log never came (seen on linux net11.0 CI).
The test now waits for the listener to log the closed channel first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Code coverage

✅ Coverage gate passed.

Check Result Threshold
✅ Project line rate 89.23% (495152/554932 lines) >= 70.00%
✅ Project branch rate 79.77% >= 60.00%
✅ Patch coverage 85.26% (81/95 changed lines) >= 60.00% (<= 100 changed lines, advisory)
ℹ️ Baseline delta (advisory) +15.63 pp 73.60% recorded
Uncovered changed lines
  • src/Opc.Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs: 232, 233, 234, 271, 272, 273
  • src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs: 1460, 1461, 1483, 1489, 1490, 1491, 1492, 1493

Coverage is above the recorded baseline - consider ratcheting coverage-thresholds.json.

Thresholds live in coverage-thresholds.json. Whole report before exclusions: line 88.56%, branch 79.12%.

@codecov

codecov Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.15789% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 83.62%. Comparing base (f1c928f) to head (47321b2).
⚠️ Report is 12 commits behind head on master.

Files with missing lines Patch % Lines
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 72.72% 8 Missing and 1 partial ⚠️
....Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs 87.50% 6 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #5084      +/-   ##
==========================================
+ Coverage   83.61%   83.62%   +0.01%     
==========================================
  Files        3780     3786       +6     
  Lines      553717   554932    +1215     
  Branches    94457    94765     +308     
==========================================
+ Hits       462972   464080    +1108     
- Misses      59533    59559      +26     
- Partials    31212    31293      +81     
Flag Coverage Δ
actions 83.62% <83.15%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
....Core/Stack/Bindings/BufferManagerMemoryLimiter.cs 99.36% <100.00%> (+<0.01%) ⬆️
src/Opc.Ua.Core/Stack/Tcp/ChannelAsyncOperation.cs 72.07% <100.00%> (-0.87%) ⬇️
....Ua.Core/Stack/Tcp/ResponseContinuationDeferral.cs 87.50% <87.50%> (ø)
src/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.cs 86.09% <72.72%> (-0.21%) ⬇️

... and 97 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@marcschier
marcschier enabled auto-merge (squash) November 14, 2026 05:02
@marcschier marcschier added the ready Ready to merge once CI Passes label Nov 14, 2026
@marcschier
marcschier disabled auto-merge November 14, 2026 05:03
@marcschier
marcschier requested a balanced review from Copilot November 14, 2026 05:03
@marcschier marcschier removed the ready Ready to merge once CI Passes label Nov 14, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical defects in deferred-response draining can deadlock callers or leave response tasks unresolved under sustained synchronous traffic and cross-thread receive-loop cleanup.

3 open issues

Review effort: Balanced

Review fixes for the response continuation deferral:

- A thread holds one deferred completion. A later response completes the
  held one on the pool: two completions drained inline in turn deadlocked
  when the first continuation blocked until the second request completed.
- A held completion goes to the pool after the loop dispatched four more
  chunks without its receive going pending, so a busy channel whose
  receives keep completing synchronously does not hold a response back.
  This replaces the cap of 16, past which the held ones stayed unsignalled.
- The loop completes a held completion in a finally of the loop method
  itself, on the thread that dispatched the last chunk, not in a wrapper
  that could resume on another thread.
- A loop that resumed inside another loop's dispatch leaves the inline
  completion to the outer loop, which may hold locks.

Client work items per request stay at 1; client CPU per request on .NET 11
-1 to -28 %, throughput 0 to +2 %.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A blocking buffer rent can indefinitely stall an already-received response when the buffer budget is exhausted, with neither cancellation nor the chunk-count bound able to release it.

1 open issue
3 resolved since last review

Review effort: Balanced

The next receive can rent its buffer synchronously from the process
buffer budget, which blocks while the budget is exhausted. A response the
receive loop thread held stayed unsignalled meanwhile, and its caller may
be the one that returns the budget. The limiter now completes the response
held on the calling thread on the pool before it waits for capacity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Inline receive completions can synchronously re-enter request continuations and deadlock; inline-completion nesting must be tracked, reentrant completions dispatched to the pool, and a regression test added using a default TaskCompletionSource.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

High severity Prevent nested inline receive continuations from deadlocking

src/​Opc.Ua.Core/​Stack/​Tcp/​ResponseContinuationDeferral.cs:168

If an inline request continuation completes a receive backed by a default TaskCompletionSource, the receive loop can re-enter synchronously and run a second request continuation inline. If that second continuation waits for the first caller's task, both deadlock: the pending slot has already been cleared, and t_depth does not track inline completions. Track inline-completion nesting and send reentrant completions to the pool; add a regression test whose receive source omits RunContinuationsAsynchronously.

1 resolved since last review

Review effort: Balanced

A continuation the receive loop's thread runs inline can complete the
loop's receive synchronously (a source without asynchronous
continuations, as with an in-process peer). The loop then resumes on that
stack, defers the next response and, when it suspends, ran that one inline
too, nested in the first: a second continuation that waited for the first
never returned. The thread now counts its inline completions, and a loop
that suspends inside one completes its response on the pool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@romanett
romanett merged commit c0f9263 into master Nov 14, 2026
179 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants